package com.saturn.titan.web.utils;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;

import com.saturn.titan.core.bean.PlatformEmp;
import com.saturn.titan.core.bean.base.BusiBillOprField;
import com.saturn.titan.core.exception.DataHaveChangedException;
import com.saturn.titan.web.service.ShiroDbRealm.ShiroUser;

public class CRMUtil {
	
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	/**
	 * 获取当前登录用户的机构id
	 * @return
	 */
	public static ShiroUser getCurrentUser(){
		ShiroUser user = (ShiroUser)SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		return user;
	}
	
	
	/**
	 * 设置业务单据的创建人、创建时间等字段
	 * @param bean
	 */
	public static void setBusiBillOprFileForInsert(BusiBillOprField bean){
		bean.setCrtOpr(getCurrentUser().id);
		bean.setCrtDate(new Date());
	}
	
	/**
	 * 获取当前登录用户的机构id
	 * @return
	 */
	public static Long getCurrentUserOrgId(){
		return getCurrentUser().orgId;
	}
	
	/**
	 * 根据传入异常对象，判断异常是否由更新乐观锁校验引起的，及DataHaveChangedExceptiony异常
	 * @param t
	 * @return
	 */
	public static Throwable getDataHaveChangedException(Throwable t){
		Throwable tmp = t.getCause();
		do{
			if(tmp instanceof DataHaveChangedException){
				return tmp;
			}
		}while((tmp=tmp.getCause()) != null);
		
		return null;
	}
	
	public static boolean blankStr(String str){
		if(str == null || str.trim().length() == 0){
			return true;
		}
		return false;
	}
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	public static void entryptEmpPassword(PlatformEmp emp,String saltStr) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		if(saltStr != null){
			salt = saltStr.getBytes();
		}
		emp.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(emp.getPassword().getBytes(), salt, HASH_INTERATIONS);
		emp.setPassword(Encodes.encodeHex(hashPassword));
	}
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	public static void entryptEmpPassword(PlatformEmp emp) {
		entryptEmpPassword(emp,null);
	}
	
	public static void main(String[] args) {
		PlatformEmp emp = new PlatformEmp();
		emp.setPassword("111");
		
		entryptEmpPassword(emp,"08abaf909bd67a8c");
		System.out.println(emp.getSalt());
		System.out.println(emp.getPassword());
	}
}
